package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;

import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 实现过滤器需要实现Filter接口
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 该类的作用主要用于匹配url地址
    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override//                                                                                         过滤器
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //本次强制类型转换是为了使用子类的特有方法
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //1. 获取本次请求uri   http://localhost:8080/backend/index.html
        String requestURI = request.getRequestURI();

        //2 定义一批可以直接放行的资源地址
        String[] urls={"/employee/login","/backend/**","/front/**","/common/**","/user/sendMsg","/user/login","/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};

        //3. 判断本次请求的uri是否需要放行
                //调用方法
     boolean flag= checkUri(urls,requestURI);
                //本次请求的路径是属于不需要拦截的地址，可以直接放行
        if (flag){
            filterChain.doFilter(request, response);
            return;
        }

        //4. 检查是否登陆了,如果已经登陆可以直接放行
        Object employee = request.getSession().getAttribute("employee");
            if (employee!=null){
                //用户不为空的话就是已经登录
                filterChain.doFilter(request, response);return;
            }
        //前台页面的登陆校验
        Object user = request.getSession().getAttribute("user");
        if(user!=null){
            //用户已经登陆
            filterChain.doFilter(request,response);
            return;
        }

        //由于这里不是controller，所以你返回对象的时候需要自己的转换为json，并且写出
                //前端会判断返回的内容是否为notlogin，是的话跳转回登录界面
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
            response.getWriter().write(json);



    }

    private boolean checkUri(String[] urls, String requestURI) {

    //检查本次的请求是否符合放行的
            //遍历urls与返回的url比较
        for (String url : urls) {
            if (antPathMatcher.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
